package net.rokyinfo.appcontroller.auth;


import com.google.common.collect.Sets;
import com.google.protobuf.InvalidProtocolBufferException;
import net.rokyinfo.appcontroller.util.UserCacheUtil;
import net.rokyinfo.basecommon.constant.RedisPrefixConstants;
import net.rokyinfo.basedao.entity.User;
import net.rokyinfo.model.EbikeListProtos;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.Set;

/**
 * Created by Administrator on 2017-03-15.
 */
@Component
public class MyBasicAuthenticator extends BasicAuthenticator {

    @Autowired
    private ShardedJedisPool shardedJedisPool;

    public MyBasicAuthenticator() {
        this("exchange");
    }

    public MyBasicAuthenticator(String s) {
        super(s);
    }

    @Override
    public boolean checkCredentials(String name, String password) {

        ShardedJedis jedis = shardedJedisPool.getResource();

        try {
            String userInfo = jedis.get(RedisPrefixConstants.EBIKE_USER_INFO + name);

            if (StringUtils.isEmpty(userInfo)){
                return false;
            }

            user = UserCacheUtil.getUserFromRedisValue(userInfo);
            if (user != null && user.getUsername().equals(name) && user.getPassword2().equals(password)){
                return true;
            } else {
                return false;
            }


        } catch (JedisConnectionException e){

            e.printStackTrace();

        } finally {

            shardedJedisPool.returnResource(jedis);
        }

        return true;
    }
}
